package com.itobase.questionnaire.controller;

import com.itobase.questionnaire.VO.BaseInfo;
import com.itobase.questionnaire.VO.BaseParam;
import com.itobase.questionnaire.model.Submission;
import com.itobase.questionnaire.model.Survey;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.SubmitRepository;
import com.itobase.questionnaire.repository.SurveyGroupRepository;
import com.itobase.questionnaire.repository.SurveyRepository;
import com.itobase.questionnaire.service.IResultService;
import com.itobase.questionnaire.service.ISubmitService;
import com.itobase.questionnaire.service.impl.UserService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.util.Message;
import com.itobase.questionnaire.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.itobase.questionnaire.template.Constant.stuNum;
import static com.itobase.questionnaire.template.Constant.teacNum;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.query.Criteria.where;

/**
 * @author liucong
 * @date 2018/7/30
 */
@RestController
@RequestMapping(value = "result")
public class ResultController {

    @Autowired
    ISubmitService submitService;

    @Autowired
    IResultService resultService;

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    UserService userService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    SurveyGroupRepository surveyGroupRepository;


    /**
     * 获取调查中每个填写好的问卷的满意度和总满意度；
     * @param surveyId
     * @return
     */
    @GetMapping("rate")
    public Message getSatisfaction(@PageableDefault(
            direction = Sort.Direction.DESC) Pageable pageable,
                                   @RequestParam(required = false) String keyword,
                                   @RequestParam String surveyId,
                                   @RequestParam(required = false,defaultValue = "") String criteria){

        return Message.createSuc(submitService.getSatisfaction(surveyId,criteria,pageable,keyword));
    }


    /**
     * 根据题目获得答案和统计数据
     */
    @GetMapping("statistic")
    public Message getStatics(@PageableDefault(direction = Sort.Direction.DESC,sort = "submitTime") Pageable pageable,
                              @RequestParam String surveyId,
                              @RequestParam Integer orderNum,
                              @RequestParam(required = false) String criteria) {

        int pageNumber = pageable.getPageNumber();
        if(pageNumber<=0) {pageNumber=1;}
        PageRequest pageRequest = new PageRequest(pageNumber-1,pageable.getPageSize(),Sort.Direction.DESC,"submitTime");
        Criteria stuCriteria = where("identity").is(Constant.stuIdentity);
        Criteria teaCriteria = where("identity").is(Constant.teacIdentity);
        Criteria normal = where("surveyId").is(surveyId);

        if(orderNum.equals(teacNum)){
            normal = normal.andOperator(teaCriteria);
        }else if(orderNum.equals(stuNum) || orderNum.equals(5)){
            normal = normal.andOperator(stuCriteria);
        }
        Query query = Query.query(normal)
                .limit(pageRequest.getPageSize()).skip(pageRequest.getOffset()).with(pageRequest.getSort());
        List<Submission> submissionList = mongoTemplate.find(query,Submission.class);
        Long total = mongoTemplate.count(query,Submission.class);
        System.out.println(total);

        Survey survey = Optional.ofNullable(surveyRepository.findOne(surveyId)).orElseThrow(()->new RuntimeException("调查id错误"));

        if (!survey.getPrivately()) {
            PageImpl<Submission> submissionPage = new PageImpl<>(submissionList, pageable, total);
            return Message.createSuc(submitService.getStatics(survey.getId(),orderNum,submissionPage));
        }
        String surveyGroupId = Optional.ofNullable(survey.getSurveyGroupId()).orElseThrow(()->new RuntimeException("调查未绑定调查组"));

        List<String> userIds = submissionList.stream().map(Submission::getUserId).collect(Collectors.toList());
        List<BaseInfo> baseInfoList = userService.getUserInfoByIds(userIds,surveyGroupId);
        if(StringUtil.isNotEmpty(criteria)){
            List<BaseInfo> fitBaseInfo = baseInfoList.stream().filter(e->criteria.equals(e.getType())).collect(Collectors.toList());
            userIds.clear();
            fitBaseInfo.forEach(e->userIds.add(e.getId()));
        }

        Criteria submitCriteria = where("userId").in(userIds).and("surveyId").is(survey.getId());
        Aggregation aggregation = Aggregation.newAggregation(match(submitCriteria));
        submissionList = mongoTemplate.aggregate(aggregation,"submission",Submission.class).getMappedResults();
        PageImpl<Submission> submissionPage = new PageImpl<>(submissionList, pageRequest, total);
        return Message.createSuc(submitService.getStatics(survey.getId(), orderNum,submissionPage));

    }


    /**
     * 根据自定义的问卷答案查询提交；
     *
     * @param surveyId
     * @param params
     * @return
     */
    @GetMapping("answer")
    public Message getSubmitTime(@RequestParam String surveyId, @RequestParam List<BaseParam> params) {
        Survey survey = Optional.of(surveyRepository.findOne(surveyId)).orElseThrow(()->new RuntimeException("调查id错误"));
        if(survey.getPrivately()){
            return Message.createSuc(submitService.getSubmitTime(surveyId, params));
        }else{
            return Message.createErr("此调查不存在满意度计算");
        }
    }

    /**
     * 根据调查id获得绑定人员的完成情况
     * 这里的criteria筛选条件仅为调查组人员类型.
     * @param id 调查id
     * @return 完成情况
     */
    @GetMapping("complete")
    public Message getComplete(@PageableDefault(direction = Sort.Direction.DESC) Pageable pageable,
                               @RequestParam(required = false) String keyword,
                               @RequestParam String id,
                               @RequestParam(required = false) String criteria) {
        if (surveyRepository.findOne(id)==null) {
            return Message.createErr("调查不存在");
        }
        if (!surveyRepository.findOne(id).getPrivately()) {
            return Message.createSuc(submitService.getCompleteAnonymous(id,pageable));
        }
        List<User> users = new ArrayList<>(surveyRepository.findOne(id).getUserList());

        return Message.createSuc(submitService.getUserByComplete(id, users,criteria,pageable,keyword));
    }



    @GetMapping("excel/{id}")
    public Message getResultExcel(@PathVariable String id, HttpServletResponse response) {
        if (surveyRepository.findOne(id)==null) {
            return Message.createErr("调查不存在");
        }
        Integer exportItems = submitService.getResultExcel(id, response);
        return Message.createSuc("成功导出" + exportItems + "条数据");
    }

    /**
     * 导出满意度的excel
     * @param id
     * @param response
     * @return
     */
    @GetMapping("rate/excel/{id}")
    public Message getRateExcel(@PathVariable String id,HttpServletResponse response){
        if (surveyRepository.findOne(id)==null) {
            return Message.createErr("调查不存在");
        }
        Integer exportItems = resultService.getRateExcel(id,response);
        return Message.createSuc("成功导出" + exportItems + "条数据");

    }




    @GetMapping("person")
    public Message getResultPerson(@RequestParam String submitId) {

        return Message.createSuc(resultService.getResultPerson(submitId));
    }

    /**
     * 根据调查id和user的id获得这个人答卷
     * @return
     */
    @GetMapping("person2")
    public Message getResultPerson2(@RequestParam String surveyId,@RequestParam String userId){
        Submission submission = submitRepository.findByUserIdAndSurveyId(userId,surveyId);
        return Message.createSuc(resultService.getResultPerson(submission.getId()));
    }


    @DeleteMapping
    public Message deleteSubmit(@RequestParam String submitId) {
        submitRepository.delete(submitId);
        return Message.createSuc("删除成功");
    }


    @GetMapping("result")
    public Message getResult(HttpServletResponse response)
    {
        Integer exportItems = resultService.getResultExcel(response);
        return Message.createSuc(exportItems);
    }

    @GetMapping("result2")
    public Message getResult2(HttpServletResponse response,
                              @RequestParam(required = false) String surveyGroupId){
        resultService.getUnsubTeacher(response,surveyGroupId);
        return Message.createSuc("");
    }

    @GetMapping("result3")
    public Message getResult3(){
        return Message.createSuc(resultService.getResult());
    }

}
